<?php
namespace Home\Controller;
use Think\Controller;
use Think\Controller\RestController;
use Home\Common\Response;
use Home\Common\BizCode;
class AddressController extends RestController {
  private $user;
  public function _initialize(){
    $this->user = session('user');

    if(!$this->user){
      $response = new Response();
      $response->setFailState('UN_LOGIN');
      $this->response($response, 'json');
      exit;
    }
  }

  public function add()
  {
    $response = new Response();
    $data = I('post.');

    $data['user_id'] = $this->user['user_id'];
    $num = array_count_values($data)[''];
    if($num == 0){
      // 没有空的字段

      $Dao = M('User_address');
      $id = $Dao->add($data);
      if($id){
        $data['address_id'] = $id;
        $response->addData('address', $data);
      } else {
        $response->setFailState('OPERATE_DATABASE_ERROR');
      }
    } else {
      $response->setFailState('PARAM_INVALID');
    }

    $this->response($response, 'json');
  }

  public function update() {
    $response = new Response();
    $id = I('get.id');
    $data = I('post.');
    $data['user_id'] = $this->user['user_id'];
    $data['address_id'] = $id;
    $Dao = M('User_address');

    $result = $Dao->where('user_id = %d and address_id = %d', $data['user_id'] , $data['address_id'])->find();
    if($result){
      if(!$Dao->save($data)){
        $response->setFailState('OPERATE_DATABASE_ERROR');
      }
    } else {
      $response->setFailState('ADDRESS_NOT_EXIST_ERROR');
    }

    $this->response($response, 'json');
  }

  public function getAll()
  {
    $response = new Response();
    $data['user_id'] = $this->user['user_id'];
    $Dao = M('User_address');

    $result = $Dao->where('user_id = %d', $data['user_id'])->order('user_address.default desc')->select();

    $response->addData('addresses', $result);
    $this->response($response, 'json');
  }
  public function getDefault()
  {
    $response = new Response();
    $Dao = M('User_address');
    $data['user_id'] = $this->user['user_id'];

    $result = $Dao->where('user_address.user_id = %d and user_address.default=1', $data['user_id'])->find();
    $response->addData('address', $result);

    $this->response($response, 'json');
  }

  public function deleteAddr(){
    $response = new Response();
    $id = I('id');
    $Dao = M('User_address');
    $Dao->where('user_id = %d and address_id = %d', $this->user['user_id'], $id)->delete();

    $this->response($response, 'json');
  }

  public function setDefault()
  {
    $response = new Response();
    $id = I('address_id');
    if(!empty($id)){
      $Dao = M('User_address');
      $Dao->where('user_id = %d', $this->user['user_id'])->setField('default', '0');
      $Dao->where('user_id = %d and address_id = %d', $this->user['user_id'], $id)->setField('default', '1');
    } else {
      $response->setFailState('PARAM_INVALID');
    }

    $this->response($response, 'json');
  }
}
